package org.tong.interceptors;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.tong.log.LogUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Spring 拦截器，拦截外部http请求，
 * 如果，请求头内有TRACE_ID则将其放入MDC中，表示此次请求为其它调用的延续
 * 否则，生成一个新的TRACE_ID放入MDC，表示此次请求为一个新的调用链路
 */
@Component
public class LogHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(LogUtils.TRACE_ID);
        if (!StringUtils.isEmpty(traceId)) {
            MDC.put(LogUtils.TRACE_ID, traceId);
        } else {
            MDC.put(LogUtils.TRACE_ID, LogUtils.getTraceId());
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 当前请求完成后，删除当前线程的TRACE_ID标记
        if (!StringUtils.isEmpty(MDC.get(LogUtils.TRACE_ID))) {
            MDC.remove(LogUtils.TRACE_ID);
        }
    }
}
